/*
 * Copyright 2025 The JA-SIG Collaborative. All rights reserved.
 * distributed with this file and available online at
 */
package com.lap.auth.adapter.driving.persistence.job.repository;

import com.lap.auth.adapter.driving.persistence.job.JobConverter;
import com.lap.auth.adapter.driving.persistence.job.mapper.JobMapper;
import com.lap.auth.adapter.driving.persistence.job.po.JobPo;
import com.lap.auth.domain.job.Job;
import com.lap.auth.domain.job.repository.JobRepository;
import java.util.Optional;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Repository;

@RequiredArgsConstructor
@Repository
public class JobRepositoryImpl implements JobRepository {

  private final JobConverter jobConverter;
  private final JobMapper jobMapper;

  @Override
  public Integer save(Job job) {
    JobPo jobPo = jobConverter.toPo(job);
    if (job.isNew()) {
      jobMapper.insert(jobPo);
      return jobPo.getId();
    }
    return jobMapper.updateByPrimaryKey(jobPo);
  }

  @Override
  public int deleteById(Integer id) {
    return jobMapper.deleteByPrimaryKey(id);
  }

  @Override
  public Optional<Job> findById(Integer id) {
    var jobPo = jobMapper.selectByPrimaryKey(id);
    return Optional.ofNullable(jobConverter.toDomain(jobPo));
  }

  @Override
  public Optional<Job> findByCode(String code) {
    var jobPo = jobMapper.selectByCode(code);
    return Optional.ofNullable(jobConverter.toDomain(jobPo));
  }
}
